package com.rightsidetech.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.system.dtos.request.adverts.AdvertsLoadSaveReq;
import com.rightsidetech.system.dtos.request.adverts.AdvertsLoadUpReq;
import com.rightsidetech.system.dtos.request.adverts.AdvertsPageReq;
import com.rightsidetech.system.dtos.request.adverts.CloseLoadReq;
import com.rightsidetech.system.dtos.response.adverts.AdvertsPageResp;
import com.rightsidetech.system.dtos.response.adverts.AppAdvertsResp;
import com.rightsidetech.system.entity.adverts.SysAdvertsLoad;
import com.rightsidetech.system.mapper.SysAdvertsLoadMapper;
import com.rightsidetech.system.service.SysAdvertsLoadService;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service("sysAdvertsLoadService")
public class SysAdvertsLoadServiceImpl implements SysAdvertsLoadService {

    @Resource
    private SysAdvertsLoadMapper sysAdvertsLoadMapper;

    @Override
    public ResponseData saveAdverts(AdvertsLoadSaveReq req,String createrName) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Date startDate = req.getStartDate();
        Date endDate = req.getEndDate();
        if(endDate.compareTo(startDate) <= 0){
            return ResponseData.fail("发布结束时间不可以小于或等于开始时间");
        }
        if(getYesterday().compareTo(startDate) > 0){
            return ResponseData.fail("开始时间不可小于今天");
        }
        Long count = sysAdvertsLoadMapper.selectCountByTopic(req.getTopicName());
        if(count > 0){
            return ResponseData.fail("主题已存在");
        }
        Long dateCount = sysAdvertsLoadMapper.selectCountByStartDate(startDate,req.getPlatform(),null);
        if(dateCount > 0){
            return ResponseData.fail("在此时间内已存在同平台的广告页");
        }
        SysAdvertsLoad load = new SysAdvertsLoad();
        load.setTopicName(req.getTopicName());
        load.setPicture(req.getPicture());
        load.setPlatform(req.getPlatform());
        load.setStartDate(req.getStartDate());
        load.setEndDate(parseTime(req.getEndDate()));
        load.setIsClose((byte)0);
        load.setCreaterName(createrName);
        load.setCreatedAt(new Date());
        load.setIsDeleted((byte)0);
        if (sysAdvertsLoadMapper.insertSelective(load) <= 0) {
            return ResponseData.fail("添加失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData<PageInfo<AdvertsPageResp>> page(AdvertsPageReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        PageHelper.startPage(req.getPageNo(),req.getPageSize());
        List<AdvertsPageResp> result = sysAdvertsLoadMapper.selectPage(req);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (AdvertsPageResp resp : result) {
            Date startDa = resp.getStartDa();
            Date endDa = resp.getEndDa();
            resp.setStartDate(format.format(startDa));
            resp.setEndDate(format.format(endDa));
            int i = isEffectiveDate(new Date(), startDa, endDa) ? 0 : 1;
            resp.setStatus((byte)i);
        }
        return ResponseData.success(new PageInfo<>(result));
    }

    @Override
    public ResponseData update(AdvertsLoadUpReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysAdvertsLoad advertsLoad = sysAdvertsLoadMapper.selectByPrimaryKey(req.getId());
        if(ObjectUtil.isEmpty(advertsLoad) || advertsLoad.getIsDeleted() == 1){
            return ResponseData.fail("没有找到需要更新的数据");
        }
        Date startDate = req.getStartDate();
        Date endDate = req.getEndDate();
        if(!startDate.equals(advertsLoad.getStartDate()) || !endDate.equals(advertsLoad.getEndDate())){
            if(endDate.compareTo(startDate) <= 0){
                return ResponseData.fail("发布结束时间不可以小于或等于开始时间");
            }
            if(getYesterday().compareTo(startDate) > 0){
                return ResponseData.fail("开始时间不可小于今天");
            }
        }
        if(!req.getTopicName().equals(advertsLoad.getTopicName())){
            if (sysAdvertsLoadMapper.selectCountByTopic(req.getTopicName()) > 0) {
                return ResponseData.fail("已存在相同名称的主题");
            }
        }
        Long count = sysAdvertsLoadMapper.selectCountByStartDate(startDate, req.getPlatform(), req.getId());
        if(count > 0){
            return ResponseData.fail("在此时间内已存在同平台的广告页");
        }
        SysAdvertsLoad record = new SysAdvertsLoad();
        record.setId(req.getId());
        record.setTopicName(req.getTopicName());
        record.setPicture(req.getPicture());
        record.setPlatform(req.getPlatform());
        record.setStartDate(req.getStartDate());
        record.setEndDate(parseTime(req.getEndDate()));
        record.setUpdatedAt(new Date());
        if (sysAdvertsLoadMapper.updateByPrimaryKeySelective(record) <= 0) {
            return ResponseData.fail("修改失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    private boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime() || nowTime.getTime() == endTime.getTime()) {
            return true;
        }
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);
        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);
        Calendar end = Calendar.getInstance();
        end.setTime(endTime);
        if(date.after(begin) && date.before(end)){
            return true;
        }
        return false;
    }

    @Override
    public ResponseData del(DelReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysAdvertsLoad load = sysAdvertsLoadMapper.selectByPrimaryKey(req.getId());
        if(ObjectUtil.isEmpty(load) || load.getIsDeleted() == 1){
            return ResponseData.fail("未找到需要删除的数据");
        }
        load = new SysAdvertsLoad();
        load.setId(req.getId());
        load.setIsDeleted((byte)1);
        if (sysAdvertsLoadMapper.updateByPrimaryKeySelective(load) <= 0) {
            return ResponseData.fail("删除失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData isCloseLoad(CloseLoadReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysAdvertsLoad load = sysAdvertsLoadMapper.selectByPrimaryKey(req.getId());
        if(ObjectUtil.isEmpty(load) || load.getIsDeleted() == 1){
            return ResponseData.fail("未找到操作的数据");
        }
        SysAdvertsLoad record = new SysAdvertsLoad();
        record.setId(req.getId());
        record.setIsClose(req.getIsClose());
        if (sysAdvertsLoadMapper.updateByPrimaryKeySelective(record) <= 0) {
            return ResponseData.fail("操作失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData<AppAdvertsResp> getAdverts(Byte platform) {
        AppAdvertsResp result = sysAdvertsLoadMapper.selectAppAdverts(platform);
        return ResponseData.success(result);
    }

    @Override
    public AdvertsPageResp selectById(Long id) {
        return sysAdvertsLoadMapper.selectById(id);
    }


    private Date getYesterday(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH) - 1,23,59,59);
        return calendar.getTime();
    }

    public Date parseTime(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH),23,59,59);
        return calendar.getTime();
    }
}
